﻿using System.Data.Common;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace DAL
{
    public class DaoFactory
    {
        public Database db;
        public DbTransaction transaction;
        public DbConnection connection;

        /// <summary>
        /// Cria a Conexão com a base de dados
        /// </summary>
        public DaoFactory()
        {
            ConectaDatabase();
        }

        /// <summary>
        /// Cria a Conexão com a base de dados
        /// </summary>
        public DaoFactory(string strConexao)
        {
            ConectaDatabase(strConexao);
        }

        /// <summary>
        /// Faz a conexão usando o nome default da conexão no web.config
        /// </summary>
        /// <param name="UsaTransaction">True caso use transação, False não utiliza transação</param>
        public DaoFactory(bool UsaTransaction)
        {
            ConectaDatabase();
            connection = db.CreateConnection();
            connection.Open();

            if (UsaTransaction)
                transaction = connection.BeginTransaction();
        }

        /// <summary>
        /// Faz a conexão usando o nome default da conexão no web.config
        /// </summary>
        /// <param name="UsaTransaction">True caso use transação, False não utiliza transação</param>
        public DaoFactory(bool UsaTransaction, string strConexao)
        {
            ConectaDatabase(strConexao);
            connection = db.CreateConnection();
            connection.Open();

            if (UsaTransaction)
                transaction = connection.BeginTransaction();
        }

        private void ConectaDatabase()
        {
            db = CreateDatabase();

        }

        private void ConectaDatabase(string strConexao)
        {
            db = CreateDatabase(strConexao);

        }

        private Database CreateDatabase()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ATB.Provider.ConnectionString"].ToString();
            string provider = "System.Data.SqlClient";
            return new GenericDatabase(connectionString, DbProviderFactories.GetFactory(provider));
        }

        private Database CreateDatabase(string strConexao)
        {
            string connectionString = ConfigurationManager.ConnectionStrings[strConexao].ToString();
            string provider = "System.Data.SqlClient";
            return new GenericDatabase(connectionString, DbProviderFactories.GetFactory(provider));
        }
    }
}
